package minioutil

import (
	"bytes"
	"io"
	"log"

	"github.com/google/uuid"
	"github.com/minio/minio-go"
)

// UUID 生成没有破折号的 UUID
func uid() string {
	return uuid.NewString()
}

// 上传文件
// filetype是文件的后缀
func Upload(by []byte, filetype string, buckets ...string) (string, error) {
	filename := uid() + "." + filetype
	var bucket string
	if len(bucket) == 0 {
		bucket = Config.Bucket
	} else {
		bucket = buckets[0]
	}
	_, err := Client.PutObject(bucket, filename, bytes.NewReader(by), int64(len(by)), minio.PutObjectOptions{})
	if err != nil {
		log.Println("minio上传文件失败", err.Error())
		return "", err
	}
	return filename, nil
}

// 下载文件返回文件流
func Download(filename string, buckets ...string) ([]byte, error) {
	var bucket string
	if len(bucket) == 0 {
		bucket = Config.Bucket
	} else {
		bucket = buckets[0]
	}
	obj, err := Client.GetObject(bucket, filename, minio.GetObjectOptions{})
	if err != nil {
		log.Println("minio获取文件失败", err.Error())
		return nil, err
	}
	by, err := io.ReadAll(obj)
	if err != nil {
		log.Println("读取文件流失败", err.Error())
	}
	return by, nil
}


// 文件预览是文件的格式
// 这里需要自动拼接文件地址
// 例如 Preview 的路由是/file/previe那么图片的预览地址就是/file/previe?{key}={filename}
// 注意需要在header中设置Content-Type
func Preview(filename string, buckets ...string) ([]byte, string, error) {
	var bucket string
	if len(bucket) == 0 {
		bucket = Config.Bucket
	} else {
		bucket = buckets[0]
	}
	obj, err := Client.GetObject(bucket, filename, minio.GetObjectOptions{})
	if err != nil {
		log.Println("minio获取文件失败", err.Error())
		return nil, "", err
	}
	by, err := io.ReadAll(obj)
	if err != nil {
		log.Println("读取文件流失败", err.Error())
		return nil, "", err
	}
	info, err := obj.Stat()
	if err != nil {
		log.Println("获取文件信息失败", err.Error())
		return by, "application/octet-stream", nil
	}
	return by, info.ContentType, nil
}
